import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, SearchBar } from 'antd-mobile'
import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { useDebounceFn } from 'ahooks'
import { useDispatch, useSelector } from 'react-redux'
import {
  addHistory,
  clearHistory,
  clearResObj,
  delHistory,
  getSuggestionList,
} from '@/store/actions/search'
import { RootState } from '@/types/store'

const Search = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const [key, setKey] = useState('')
  const { suggestion, history: historyList } = useSelector(
    (state: RootState) => state.search
  )
  const [isSearching, setIsSearching] = useState(false)

  const { run: getSuggestList } = useDebounceFn(
    (val) => {
      console.log('发送请求')
      if (!val) return
      dispatch(getSuggestionList(val))
    },
    {
      wait: 500,
    }
  )

  // 处理高亮
  const highLight = (str: string) => {
    // str => 要处理的字符串
    // key => 搜索关键字
    const reg = new RegExp(key, 'gi')
    return str.replace(reg, (match) => `<span>${match}</span>`)
  }

  // 统一处理搜索
  const onSearch = (str: string) => {
    if (str.trim() === '') return
    dispatch(addHistory(str))
    dispatch(clearResObj())
    history.push(`/search/result?keyword=${str}`)
  }

  // 清除历史全部
  const clearAll = () => {
    dispatch(clearHistory())
  }

  // 删除某个历史
  const onDel = (item: string) => {
    dispatch(delHistory(item))
  }

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span className="search-text" onClick={() => onSearch(key)}>
            搜索
          </span>
        }
      >
        <SearchBar
          placeholder="请输入关键字搜索"
          value={key}
          onChange={(val) => {
            if (val) {
              setIsSearching(true)
            } else {
              setIsSearching(false)
            }
            setKey(val)
            getSuggestList(val)
          }}
        />
      </NavBar>

      {/* 搜索历史 */}
      {true && (
        <div
          className="history"
          style={{
            display: isSearching ? 'none' : 'block',
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={clearAll}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {historyList.map((item, index) => (
              <span key={index} className="history-item">
                <span className="text-overflow" onClick={() => onSearch(item)}>
                  {item}
                </span>
                <Icon type="iconbtn_essay_close" onClick={() => onDel(item)} />
              </span>
            ))}
          </div>
        </div>
      )}

      <div className={classnames('search-result', isSearching ? 'show' : '')}>
        {suggestion.map((item, index) => (
          <div
            className="result-item"
            key={index}
            onClick={() => onSearch(item)}
          >
            <Icon className="icon-search" type="iconbtn_search" />
            <div
              className="result-value text-overflow"
              dangerouslySetInnerHTML={{ __html: highLight(item) }}
            ></div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default Search
